package com.dotstone.chipism.ui.login;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.activity.AddHouseActivity;
import com.dotstone.chipism.activity.BaseActivity;
import com.dotstone.chipism.activity.DemoActivity;
import com.dotstone.chipism.activity.ForgetPwdActivity;
import com.dotstone.chipism.activity.MainActivity;
import com.dotstone.chipism.activity.RegisterActivity;
import com.dotstone.chipism.activity.RegisterActivity1;
import com.dotstone.chipism.bean.Home;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.ui.login.presenter.impl.LogInPresenterImpl;
import com.dotstone.chipism.ui.login.view.LogInView;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.PhoneUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends BaseActivity implements LogInView{
	private EditText mAccountEdit; // 帐号输入框
	private EditText mPasswordEdit;// 密码输入框
	private Button mLoginBtn;// 登录按钮
	private TextView mRegisterTv;// 注册
	private TextView mForgetPwdTv;// 忘记密码
	private SVProgressHUD mSVProgressHUD;
	private Button mWechatBtn;
	private Button mDemoBtn;
	private String access_token;
	private String openid;

	LogInPresenterImpl loginPresenter;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_btn:
			// Intent intent3 = new
			// Intent(LoginActivity.this,MainActivity.class);
			// startActivity(intent3);
			if (NetUtil.isNetworkAvailable(LoginActivity.this)) {
				// ToastShow.Show(getApplicationContext(), HttpURL.LOGIN_URL);
				login();
			} else {
				ToastShow.Show(getApplicationContext(), getString(R.string.nonetwork));
			}
			break;
		case R.id.register_tv:
			Intent intent2 = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(intent2);
			finish();
			break;
		case R.id.forget_password_tv:
			Intent intent1 = new Intent(LoginActivity.this, ForgetPwdActivity.class);
			intent1.putExtra("fromLogin", true);
			startActivity(intent1);
			finish();
			break;
		case R.id.wechat_btn:
			// showToast("暂未实现");
			loginWithWechat();
			break;

		case R.id.demo_btn:
			Intent intent = new Intent(LoginActivity.this, DemoActivity.class);
			// startActivity(intent);
			showToast("暂未实现");
			break;

		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_login;
	}

	@Override
	public void initView(View view) {
		loginPresenter = new LogInPresenterImpl(this);
		// TODO Auto-generated method stub
		// regToWx();
		mSVProgressHUD = new SVProgressHUD(LoginActivity.this);
		mAccountEdit = $(R.id.username_ed);
		mPasswordEdit = $(R.id.pwd_ed);
		mLoginBtn = $(R.id.login_btn);
		mRegisterTv = $(R.id.register_tv);
		mForgetPwdTv = $(R.id.forget_password_tv);
		mWechatBtn = $(R.id.wechat_btn);
		mDemoBtn = $(R.id.demo_btn);
		mLoginBtn.setOnClickListener(this);
		mRegisterTv.setOnClickListener(this);
		mForgetPwdTv.setOnClickListener(this);
		mWechatBtn.setOnClickListener(this);
		mDemoBtn.setOnClickListener(this);
		mAccountEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mAccountEdit.setHint("");
				} else {
					if (mAccountEdit.getText().toString().length() == 0) {
						mAccountEdit.setHint(getString(R.string.phone_num));
					}
				}
			}
		});
		mPasswordEdit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					mPasswordEdit.setHint("");
				} else {
					if (mPasswordEdit.getText().toString().length() == 0) {
						mPasswordEdit.setHint(getString(R.string.login_pwd_hint));
					}
				}
			}
		});
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	/**
	 * 方法：login 用途：登录 判断输入内容是否符合 发送网络请求 根据返回数据做出处理
	 */
	private void login() {
		final String phone = mAccountEdit.getText().toString().trim();
		final String pwd = mPasswordEdit.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.phone_not_null),
					Toast.LENGTH_SHORT);
			toast.show();
			return;
		}
		if (!PhoneUtil.isMobileNO(phone)) {
			Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.phone_not_right),
					Toast.LENGTH_SHORT);
			toast.show();
			return;
		}
		if (TextUtils.isEmpty(pwd)) {
			Toast toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.pwd_not_null),
					Toast.LENGTH_SHORT);
			toast.show();
			return;
		}
		mSVProgressHUD.showWithStatus("正在提交");
//		Log.i("登录", "开始登录" + phone + "---" + pwd);
//		loginPresenter.requestLogIn(phone , pwd);

		RequestParams params = new RequestParams(HttpURL.LOGIN_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("mobile", phone);
			obj.put("password", pwd);
			obj.put("reqAddress", "未知");
			obj.put("reqOs", "3");// android3 ios4
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
//
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					int resultCode = jsonObject.optInt("resultCode");

					if (resultCode == 1) {
						int user_id = jsonObject.getJSONObject("data").getJSONObject("userLogin").optInt("userId");
						String nickname = jsonObject.getJSONObject("data").getJSONObject("userInfo").optString("name");
						String password = jsonObject.getJSONObject("data").getJSONObject("userInfo")
								.optString("password");
						String token = jsonObject.getJSONObject("data").getJSONObject("userLogin").optString("token");
						String shopToken = jsonObject.getJSONObject("data").getJSONObject("userLogin")
								.optString("shopToken");
						SocketManager.getInstance().user_id = user_id + "";
						SocketManager.getInstance().token = token;
						Log.e("wmy", "token = " + token);
						Log.e("wmy", "shopToken = " + shopToken);
						Log.e("wmy", "nickname = " + nickname);
						try {
							String iconUrl = jsonObject.getJSONObject("data").getJSONObject("userInfo")
									.optString("iconUrl");
							String userName = jsonObject.getJSONObject("data").getJSONObject("userInfo")
									.optString("userName");
							SPUtils.put(LoginActivity.this, "nickname", nickname);
							SPUtils.put(LoginActivity.this, "user_id", user_id + "");
							if (!shopToken.equals("") && shopToken != null) {
								SPUtils.put(LoginActivity.this, "shopToken", shopToken);
							}
							SPUtils.put(LoginActivity.this, "iconUrl", iconUrl);
							SPUtils.put(LoginActivity.this, "userName", userName);
						} catch (Exception e) {

						}
						getShopToken(phone, password);
						SPUtils.put(LoginActivity.this, "pwd", pwd);
						SPUtils.put(LoginActivity.this, "password", password);
						Log.i("login", "login " + (String) SPUtils.get(getApplicationContext(), "pwd", ""));
						SPUtils.put(LoginActivity.this, "user_name", phone);
						SPUtils.put(LoginActivity.this, "user_id", user_id + "");
						SPUtils.put(LoginActivity.this, "token", token);
						// 登录成功后请求房屋数据
						getHouse(token);
						MobclickAgent.onProfileSignIn(phone);
						// Intent intent = new Intent(LoginActivity.this,
						// MainActivity.class);
						// startActivity(intent);
						//
						// finish();
					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(LoginActivity.this, errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
					mLoginBtn.setVisibility(View.VISIBLE);
					mSVProgressHUD.dismiss();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("wmy", "错误" + ex.getMessage());
				// mLoginBtn.setVisibility(View.VISIBLE);
				// Toast.makeText(getApplicationContext(), "网络错误，请重试！",
				// Toast.LENGTH_SHORT).show();
				// mSVProgressHUD.dismiss();
				login();
			}

			@Override
			public void onCancelled(CancelledException cex) {
				Log.e("wmy", "取消");
				mLoginBtn.setVisibility(View.VISIBLE);
				Toast.makeText(getApplicationContext(), "网络错误，请重试！", Toast.LENGTH_SHORT).show();
				mSVProgressHUD.dismiss();
			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});

	}

	private void getShopToken(String phone, String pwd) {
		RequestParams params = new RequestParams("http://api.shop.soochowlightpower.com/v2/xin.auth.signin");
		// params.addHeader("X-ECAPI-Authorization", (String)
		// SPUtils.get(getApplicationContext(), "shopToken", ""));
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("username", phone);
			obj.put("password", pwd);
			Log.e("wmy", " get ShopToken = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "get ShopToken =" + result);
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(result);
					JSONObject jo = jsonObject.getJSONObject("data");
					JSONObject userLogin = jo.getJSONObject("userLogin");
					String shopToken = userLogin.optString("token");
					Log.i("wmy", "shopToken = " + shopToken);
					SPUtils.put(getApplicationContext(), "shopToken", shopToken);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {
				Log.e("wmy", "get all dingdan cancel");
			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				// lt.error();
				Log.e("wmy", "get all dingdan error");
			}

			@Override
			public void onFinished() {
				Log.e("wmy", "get all dingdan finish");
			}
		});
	}

	private void getHouse(String token) {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token", token);
			obj.put("deviceId", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");

					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");
						if (ja.length() < 1) {
							Intent intent = new Intent(LoginActivity.this, AddHouseActivity.class);
							startActivity(intent);
							finish();
						} else {
							for (int i = 0; i < ja.length(); i++) {
								String hid = ja.getJSONObject(i).getString("hid");
								String userId = ja.getJSONObject(i).getString("userId");
								String homeName = ja.getJSONObject(i).getString("homeName");
								int status = ja.getJSONObject(i).getInt("status");
								if (status == 1) {
									DeviceManager.getInstance().homeName = homeName;
									DeviceManager.getInstance().hid = hid;
								}
								Home home = new Home(hid, userId, homeName, status);
								DeviceManager.getInstance().addHome(home);
							}
							if (DeviceManager.getInstance().hid.length() != 0) {
								Intent intent = new Intent(LoginActivity.this, MainActivity.class);
								startActivity(intent);
								finish();
							} else {
								changeStatus(DeviceManager.getInstance().getAllHome().get(0).getHid(),
										DeviceManager.getInstance().getAllHome().get(0).getHomeName(), 1);
							}
						}

					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(LoginActivity.this, errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
					mLoginBtn.setVisibility(View.VISIBLE);
					mSVProgressHUD.dismiss();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				mLoginBtn.setVisibility(View.VISIBLE);
				Toast.makeText(getApplicationContext(), "网络错误，请重试！", Toast.LENGTH_SHORT).show();
				mSVProgressHUD.dismiss();
			}

			@Override
			public void onCancelled(CancelledException cex) {
				Log.e("Tag", "取消");
				mLoginBtn.setVisibility(View.VISIBLE);
				Toast.makeText(getApplicationContext(), "网络错误，请重试！", Toast.LENGTH_SHORT).show();
				mSVProgressHUD.dismiss();
			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}
	
	private void changeStatus(final String hid, final String name, int status) {
		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			String token = (String) SPUtils.get(getApplicationContext(), "token", "");
			try {
				obj.put("hid", hid);
				obj.put("key", "10000");
				obj.put("homeName", name);
				obj.put("handleType", "2");
				obj.put("token", token);
				obj.put("status", status);
				obj.put("requestTime", "" + System.currentTimeMillis());
				Log.e("test", "更改房屋状态 = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "成功=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");

						if (resultCode == 1) {
							DeviceManager.getInstance().hid = hid;
							DeviceManager.getInstance().homeName = name;
							Intent intent = new Intent(LoginActivity.this, MainActivity.class);
							startActivity(intent);
							finish();
						} else {
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					Log.e("Tag", "错误" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {

				}

				@Override
				public void onFinished() {
					Log.e("Tag", "完成");
				}
			});
		} else {
			// ToastShow.Show(getApplicationContext(),
			// getString(R.string.nonetwork));
		}
	}

	// private void regToWx() {
	// api = WXAPIFactory.createWXAPI(this, APP_ID, true);
	// api.registerApp(APP_ID);
	// }
	private ProgressDialog dialog;

	private void loginWithWechat() {
		dialog = new ProgressDialog(LoginActivity.this);
		UMShareAPI.get(getApplicationContext()).doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
		// UMShareAPI mShareAPI = new UmsHARE
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

	}

	UMAuthListener authListener = new UMAuthListener() {
		@Override
		public void onStart(SHARE_MEDIA platform) {
			SocializeUtils.safeShowDialog(dialog);
		}

		@Override
		public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
			SocializeUtils.safeCloseDialog(dialog);
			Log.i("wmy", "data = " + data + " action = " + action);
			Toast.makeText(LoginActivity.this, "授权成功", Toast.LENGTH_LONG).show();
			access_token = data.get("access_token");
			openid = data.get("openid");
			if (access_token != null) {
				SPUtils.put(getApplicationContext(), "access_token", access_token);
			}
			if (openid != null) {
				SPUtils.put(getApplicationContext(), "openid", openid);
				// 调用openId检查接口
				checkopenId();
			}
		}

		@Override
		public void onError(SHARE_MEDIA platform, int action, Throwable t) {
			SocializeUtils.safeCloseDialog(dialog);
			Toast.makeText(LoginActivity.this, "onError" + t.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel(SHARE_MEDIA platform, int action) {
			SocializeUtils.safeCloseDialog(dialog);
			Toast.makeText(LoginActivity.this, "onCancel", Toast.LENGTH_LONG).show();
		}
	};

	private void checkopenId() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			RequestParams params = new RequestParams(HttpURL.CHECK_OPENID);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("weixinToken", openid);
				obj.put("reqAddress", "深圳");
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("reqOs", 3);
				Log.e("test", " score order = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "score order =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							String userName = "";
							int user_id = jsonObject.getJSONObject("data").getJSONObject("userLogin").optInt("userId");
							String token = jsonObject.getJSONObject("data").getJSONObject("userLogin")
									.optString("token");
							String shopToken = jsonObject.getJSONObject("data").getJSONObject("userLogin")
									.optString("shopToken");
							SocketManager.getInstance().user_id = user_id + "";
							SocketManager.getInstance().token = token;
							Log.e("wmy", "token = " + token);
							Log.e("wmy", "shopToken = " + shopToken);
							try {
								String iconUrl = jsonObject.getJSONObject("data").getJSONObject("userInfo")
										.optString("iconUrl");
								userName = jsonObject.getJSONObject("data").getJSONObject("userInfo")
										.optString("userName");
								SPUtils.put(LoginActivity.this, "user_id", user_id + "");
								SPUtils.put(LoginActivity.this, "shopToken", shopToken);
								SPUtils.put(LoginActivity.this, "iconUrl", iconUrl);
								SPUtils.put(LoginActivity.this, "userName", userName);
							} catch (Exception e) {

							}
							// SPUtils.put(LoginActivity.this, "pwd", pwd);
							Log.i("login", "login " + (String) SPUtils.get(getApplicationContext(), "pwd", ""));
							SPUtils.put(LoginActivity.this, "user_name", userName);
							SPUtils.put(LoginActivity.this, "user_id", user_id + "");
							SPUtils.put(LoginActivity.this, "token", token);
							// 登录成功后请求房屋数据
							getHouse(token);
							MobclickAgent.onProfileSignIn(userName);
						} else {
							Intent intent = new Intent(LoginActivity.this, RegisterActivity1.class);
							intent.putExtra("openid", openid);
							startActivity(intent);
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		} else {
			ToastShow.Show(getApplicationContext(), getString(R.string.nonetwork));
		}
	}

	@Override
	public void returnLogInResult(boolean result) {

	}
}
